/**   
* @Title: HttpDownloader.java
* @Package org.xaoyaoyao.spider.downloader
* @Description: TODO
* @author xaoyaoyao
* @date Jan 25, 2019 11:14:05 AM
* @version V1.0   
*/
package org.xaoyaoyao.spider.downloader;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.xaoyaoyao.spider.enums.RequestMethodEnum;
import org.xaoyaoyao.spider.http.HttpUtil;

import com.alibaba.fastjson.JSON;

import lombok.Builder;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: HttpDownloader
 * @Description: TODO
 * @author xaoyaoyao
 * @date Jan 25, 2019 11:14:05 AM
 * 
 */
@Slf4j
@Builder
public class HttpDownloader {

	/** url **/
	private String url;

	/** 请求方式：get/post/json，为则默认get请求 **/
	private String requestMethod;

	/** 参数, post请求等 **/
	private Map<String, Object> params;

	/** 头部信息 **/
	private Map<String, Object> headerParams;

	/** cookie **/
	private String cookie;

	/** ua **/
	private String ua;

	public String download() {
		log.debug(">>>>>>>> url >> {}", url);
		log.debug(">>>>>>>> requestMethod >> {}, cookie >> {}, ua >> {}", requestMethod, cookie, ua);
		log.debug(">>>>>>>> parameters >> {}, headerParams >> {}", params, headerParams);
		if (StringUtils.isBlank(url)) {
			log.error(">>>>>>>> The url is empty!!!");
			return null;
		}
		ua = StringUtils.isBlank(ua) ? HttpUtil.DEFAULT_UA : ua;
		if (StringUtils.isNoneBlank(cookie)) {
			headerParams = MapUtils.isEmpty(headerParams) ? new HashMap<String, Object>(1) : headerParams;
			headerParams.put("Cookie", cookie);
		}
		String result = null;
		RequestMethodEnum methodEnum = RequestMethodEnum.from(requestMethod);
		if (null != methodEnum && methodEnum.equals(RequestMethodEnum.JSON)) {
			result = HttpUtil.getInstance().postRequestBody(JSON.toJSONString(params), url, null, ua, headerParams);
		} else if (null != methodEnum && methodEnum.equals(RequestMethodEnum.POST)) {
			result = HttpUtil.getInstance().post(url, params, ua, headerParams);
		} else {
			result = HttpUtil.getInstance().get(url, ua, headerParams);
		}
		log.debug(">>>>>>>> result >> {}", result);
		return result;
	}
}
